const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

// 根据id去重
const beSet = (arr) => {
  arr = arr.reverse()
  var result = [], i, j, len = arr.length;
  for (i = 0; i < len; i++) {
    for (j = i + 1; j < len; j++) {
      if (arr[i].id === arr[j].id) {
        j = ++i;
      }
    }
    result.push(arr[i]);
  }
  return result.reverse();
}

// promise 登录
const login = (ghid)=>{
  var that = this;
  return new Promise(function (resolve, reject) {
    // 调用登录接口
    wx.login({
      success: function (res) {
        if (res.code) {
          wx.request({
            url: that.globalData.url + 'accs/login',
            method: 'POST',
            data: {
              gh_id: ghid,
              code: res.code,
              id: that.globalData.userId
            },
            success: function (res) {
              that.globalData.openId = res.data.msg
              that.globalData.userId = res.data.data.userid
              that.globalData.lock = res.data.data.lock

              that.globalData.isFirstOpen = res.data.data.is_formid
              var result = {
                status: 200,
                data: res.data.data.lock
              }
              resolve(result);
            },
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg);
          var res = {
            status: 300,
            data: '错误'
          }
          reject('error');
        }
      }
    })
  });
}

module.exports = {
  formatTime: formatTime,
  beSet: beSet
}
